package main

import (
	"encoding/json"
	"fmt"
	"log"
	"mygoedu/day11/socket"
	"net"
	"strconv"
	"time"
)

func main() {
	ip := "127.0.0.1"
	port := 8080
	udpAddress, err := net.ResolveUDPAddr("udp", ip+":"+strconv.Itoa(port))
	socket.CheckError(err)

	conn, err := net.ListenUDP("udp", udpAddress)
	socket.CheckError(err)

	err = conn.SetReadDeadline(time.Now().Add(30 * time.Second))
	socket.CheckError(err)

	defer conn.Close()
	for {
		requestBytes := make([]byte, 256)
		readLen, addr, err := conn.ReadFromUDP(requestBytes)
		if err != nil {
			fmt.Println(err)
			break
		}

		socket.CheckError(err)
		log.Printf("connect to client %d\n\n", addr.Port)

		var request socket.Request
		json.Unmarshal(requestBytes[0:readLen], &request)
		log.Printf("receive request a=%d b=%d\n", request.A, request.B)

		response := socket.Response{
			Sum: request.A + request.B,
			Dur: 0,
		}
		responseBytes, err := json.Marshal(response)
		socket.CheckError(err)

		_, err = conn.WriteToUDP(responseBytes, addr)
		socket.CheckError(err)

	}
}
